package service;

import dao.SongDao;
import entity.Song;
import io.javalin.http.UploadedFile;
import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.AudioHeader;
import util.EntityConverter;
import util.FileStorageUtil;
import util.ResponseUtil;
import util.ValidationUtil;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

public class ResourceService {
    private SongDao songDao;
    
    public ResourceService() {
        this.songDao = new SongDao();
    }
    
    public Map<String, Object> uploadMusic(Long userId, String title, String artist, 
            UploadedFile musicFile, UploadedFile coverFile, UploadedFile lyricFile) throws Exception {
        
        String musicPath = null;
        String coverPath = null;
        String lyricPath = null;
        
        try {
            // 验证文件是否存在
            if (musicFile == null) {
                throw new IllegalArgumentException("音乐文件不能为空");
            }
            
            System.out.println("开始保存文件...");
            
            // 保存文件
            try {
                musicPath = FileStorageUtil.saveMusicFile(musicFile, userId);
                System.out.println("音乐文件已保存: " + musicPath);
                
                if (coverFile != null) {
                    coverPath = FileStorageUtil.saveCoverFile(coverFile, userId);
                    System.out.println("封面已保存: " + coverPath);
                }
                
                if (lyricFile != null) {
                    lyricPath = FileStorageUtil.saveLyricFile(lyricFile, userId);
                    System.out.println("歌词已保存: " + lyricPath);
                }
            } catch (IOException e) {
                System.err.println("文件保存失败: " + e.getMessage());
                throw e;
            }
            
            // 获取音频时长
            int duration = getAudioDuration(musicPath);
            System.out.println("音频时长: " + duration);
            
            // 创建歌曲实体
            Song song = new Song();
            song.setTitle(title);
            song.setArtist(artist);
            song.setMusicFilePath(musicPath);
            song.setCoverFilePath(coverPath);
            song.setLyricFilePath(lyricPath);
            song.setCreatorId(userId);
            song.setDuration(duration);
            
            System.out.println("准备保存到数据库...");
            
            // 保存到数据库
            try {
                song = songDao.create(song);
                System.out.println("数据库保存成功，ID: " + song.getSongId());
            } catch (SQLException e) {
                System.err.println("数据库保存失败: " + e.getMessage());
                throw e;
            }
            
            return ResponseUtil.success("上传成功", EntityConverter.songToMap(song));
            
        } catch (Exception e) {
            System.err.println("上传过程出错: " + e.getMessage());
            e.printStackTrace();
            
            // 清理已上传的文件
            cleanupFiles(musicPath, coverPath, lyricPath);
            
            throw e;
        }
    }
    
    // 添加一个辅助方法来清理文件
    private void cleanupFiles(String musicPath, String coverPath, String lyricPath) {
        try {
            if (musicPath != null) FileStorageUtil.deleteFile(musicPath);
            if (coverPath != null) FileStorageUtil.deleteFile(coverPath);
            if (lyricPath != null) FileStorageUtil.deleteFile(lyricPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public Map<String, Object> deleteMusic(Long userId, Long songId) {
        try {
            Song song = songDao.findById(songId);
            if (song == null) {
                return ResponseUtil.error("音乐不存在");
            }
            
            if (!song.getCreatorId().equals(userId)) {
                return ResponseUtil.forbidden();
            }
            
            // 删除物理文件
            FileStorageUtil.deleteFile(song.getMusicFilePath());
            if (song.getCoverFilePath() != null) {
                FileStorageUtil.deleteFile(song.getCoverFilePath());
            }
            if (song.getLyricFilePath() != null) {
                FileStorageUtil.deleteFile(song.getLyricFilePath());
            }
            
            // 从数据库删除
            songDao.delete(songId);
            
            return ResponseUtil.success("删除成功");
            
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.error("删除失败：" + e.getMessage());
        }
    }
    
    public Map<String, Object> getUserMusics(Long userId) {
        try {
            List<Song> songs = songDao.findByCreatorId(userId);
            List<Map<String, Object>> songList = songs.stream()
                .map(EntityConverter::songToMap)
                .collect(Collectors.toList());
                
            return ResponseUtil.success(songList);
            
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.error("获取音乐列表失败：" + e.getMessage());
        }
    }
    
    private int getAudioDuration(String musicPath) {
        try {
            AudioFile audioFile = AudioFileIO.read(new File(musicPath));
            AudioHeader audioHeader = audioFile.getAudioHeader();
            return audioHeader.getTrackLength();
        } catch (Exception e) {
            System.err.println("获取音频时长失败: " + e.getMessage());
            return 0;
        }
    }
} 